# -*- coding: utf-8 -*-

from bopress.cache import Cache
from bopress.log import Logger
from bopress.model import Options
from bopress.orm import SessionFactory, pk

__author__ = 'yezang'


# 选项值包装类
class OptionValue(object):
    def __init__(self, values):
        if not values:
            self._value = dict()
        else:
            self._value = values

    def get(self, opt_key, single=True, default=""):
        """
        得到选项值，返回单值或者多值，主要针对Admin Option Form
        :param default:
        :param opt_key:
        :param single:
        :return:
        """
        if single:
            return self._value.get(opt_key, [default])[0]
        else:
            return self._value.get(opt_key, default)

    def to_dict(self):
        return self._value

    def empty(self):
        if len(self._value.keys()) == 0:
            return True
        return False


def loads():
    """

    """
    Cache.default().delete(["bo_options"])
    s = SessionFactory.session()
    ds = s.query(Options).filter(Options.autoload == "yes").all()
    for c in ds:
        Cache.default().set(["bo_options", c.option_name], c.option_value)


def save_options(option_group_name, option_value, auto_load="yes"):
    """
    保存选项值
    :param option_group_name: 选项组名称， 需全局唯一
    :param option_value: 能序列化与反序列化的object
    :param auto_load: `yes` or `no`
    :return: option value
    """
    s = SessionFactory.session()
    o = s.query(Options).filter(Options.option_name == option_group_name).one_or_none()
    try:
        if o:
            o.option_value = option_value
            s.commit()
        else:
            o = Options()
            o.option_id = pk()
            o.option_name = option_group_name
            o.option_value = option_value
            o.autoload = auto_load
            s.add(o)
            s.commit()
        Cache.default().delete(["bo_options", o.option_name])
    except Exception as e:
        s.rollback()
        Logger.exception(e)

    return o


def get_options(option_group_name, default=None):
    """
    得到选项值
    :param default: 默认值
    :param option_group_name: 选项组名称， 需全局唯一
    :return: option value
    """
    v = Cache.default().get(["bo_options", option_group_name])
    if v:
        return v
    s = SessionFactory.session()
    v = s.query(Options.option_value).filter(Options.option_name == option_group_name).scalar()
    if v:
        # 0 永久缓存
        Cache.default().set(["bo_options", option_group_name], v, 0)
        return v
    return default


def init_form_options(option_group_name, values):
    """
    init form options.

    :param option_group_name: group name
    :param values: dict value

        values Example::
                default_value = dict()
                default_value["site_url"] = [site_url]
                default_value["site_name"] = ["BoPress"]
                default_value["site_email"] = [""]
                default_value["users_can_register"] = ["Y"]
                default_value["default_role"] = ["subscriber"]
            Or::
                default_value = dict()
                default_value["site_url"] = site_url
                default_value["site_name"] = "BoPress"
                default_value["site_email"] = ""
                default_value["users_can_register"] = "Y"
                default_value["default_role"] = "subscriber"

    """

    for k in values:
        v = values[k]
        if type(v) is not list:
            values[k] = [v]
    opts = get_form_options(option_group_name)
    if opts.empty():
        save_options(option_group_name, values)
    else:
        # append new item.
        opt_values = opts.to_dict()
        for k in values:
            v = opt_values.get(k, None)
            if not v:
                opt_values[k] = values[k]

        # clear discard item.
        for c in opt_values:
            v = values.get(c, None)
            if not v:
                del opt_values[c]

        save_options(option_group_name, opt_values)


def get_form_options(option_group_name):
    """
    得到由Admin选项表单保存的选项值
    :param option_group_name: 选项组名称， 需全局唯一
    :return: OptionValue
    """
    v = Cache.default().get(["bo_options", option_group_name])
    if v:
        return OptionValue(v)
    s = SessionFactory.session()
    v = s.query(Options.option_value).filter(Options.option_name == option_group_name).scalar()
    if v:
        # 0 永久缓存
        Cache.default().set(["bo_options", option_group_name], v, 0)
    return OptionValue(v)


def delete_options(option_group_name):
    """
    删除选项组
    :param option_group_name:选项组名称， 需全局唯一
    """
    s = SessionFactory.session()
    s.query(Options).filter(Options.option_name == option_group_name).delete()
    s.commit()
    Cache.default().delete(["bo_options", option_group_name])


def get_site_options():
    """
    get site options
    :return:
    """
    return get_form_options("bo-site-settings")


def get_smtp_options():
    """
    get smtp options
    :return:
    """
    return get_form_options("bo-site-settings")
